﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Reflection;

namespace LiteratureManage.Web.Initialization
{
    using Castle.MicroKernel.Registration;
    using Castle.Windsor;
    using Castle.Windsor.Installer;
    using MvcContrib.Castle;

    using LiteratureManage.Domain.DataAccess;
    using LiteratureManage.Domain.Services;

    public class ApplicationBootstrapper
    {
        public IWindsorContainer Container { get; private set; }

        public ApplicationBootstrapper()
        {
        }

        public void Run()
        {
            Container = new WindsorContainer();
            Container.Install(Configuration.FromXmlFile("Config/Windsor.config"));

            Container.Register(AllTypes
               .Of<IController>()
               .FromAssembly(Assembly.GetExecutingAssembly())
               .Configure(c => c.LifeStyle.Transient.Named(c.Implementation.Name.ToLower())));

            ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(Container));

            Container.Register(
                Component.For<ILiteratureDao>().ImplementedBy<LiteratureDao>(),
                Component.For<ILiteratureService>().ImplementedBy<LiteratureService>(),
                Component.For<IDBBackupService>().ImplementedBy<DBBackupService>()
                );

            //validation
            var validatorFactory = new ServiceLocatorValidatorFactory(Container);

            //xVal
            xVal.ActiveRuleProviders.Providers.Clear();
            xVal.ActiveRuleProviders.Providers.Add(new FluentValidation.xValIntegration.FluentValidationRulesProvider(validatorFactory));

            //mvc
            ModelValidatorProviders.Providers.Add(
                new FluentValidation.Mvc.FluentValidationModelValidatorProvider(validatorFactory));
            DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

            //autoMapper
            AutoMapperConfiguration.Configure();
        }
    }
}
